/*
 * task_agent.cpp
 *
 *  Created on: 2023年10月23日
 *      Author: Dylan.Gao
 */

#include <dm/export.hpp>

#define DM_API_OS_SYS DM_API_EXPORT

#include <dm/os/sys/task_agent.hpp>
#include <dm/os/sys/task_mgr.hpp>
#include <dm/os/sys/sys_mgr.hpp>
#include <dm/os/log/logger.hpp>

namespace dm{
namespace os{
namespace sys{

static const char* logModule = "CTaskAgent.sys.os.dm";

CTaskAgent* CTaskAgent::TaskAgent = nullptr;

CTaskAgent::CTaskAgent( id_t id ):m_task(CTaskMgr::ins().getPos(id)){
	if( !m_task.refresh() ){
		log().debug(THISMODULE "任务为生效id:%d",id);
	}
	TaskAgent = this;
}


bool CTaskAgent::ifCanRun( const dm::CTimeStamp& tsNow,const dm::CRunTimeStamp& rtsNow ){
	if( getId()==-1 ){	// 测试模式
		return !CSysMgr::ins().ifExit(rtsNow);
	}

	if( !m_task.refresh() ){
		log().warnning(THISMODULE "更新任务失败:%d",getId());
		return false;
	}

	switch( m_task.getState().state ){
	case STaskState::Starting:
	case STaskState::Running:
		return true;
	default:
		return false;
	}
}

bool CTaskAgent::runOnce( const dm::CTimeStamp& tsNow,const dm::CRunTimeStamp& rtsNow ){
	if( getId()==-1 ){	// 测试模式
		return !CSysMgr::ins().ifExit(rtsNow);
	}

	if( !m_task.refresh() ){
		log().warnning(THISMODULE "更新任务失败:%d",getId());
		return false;
	}

	switch( m_task.getState().state ){
	case STaskState::Starting:
	case STaskState::Running:
		m_task.updateState(STaskState::Running, tsNow, rtsNow);
		return true;
	default:
		return false;
	}
}

}
}
}
